<?php
/**
 * Created by PhpStorm.
 * User: 554665488
 * Date: 2018-7-9
 * Time: 15:03
 * @description:
 * @Author: yfl
 * @QQ 554665488
 */

namespace App\Api\V1;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Facades\JWTAuth;

//use Tymon\JWTAuth\Middleware\GetUserFromToken;

class TokenController extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;


    public function authenticate(Request $request)
    {

//          return '1111'; // grab credentials from the request
        $payload = $request->only('email', 'password');

        try {
            // attempt to verify the credentials and create a token for the user
            if (! $token = JWTAuth::attempt($payload)) {
                return response()->json(['error' => 'invalid_credentials'], 401);
            }
        } catch (JWTException $e) {
            // something went wrong whilst attempting to encode the token
            return response()->json(['error' => 'could_not_create_token'], 500);
        }
//eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC8xMjcuMC4wLjE6ODA4M1wvYXBpXC9nZXRUb2tlbiIsImlhdCI6MTUzMTEzMTM3OCwiZXhwIjoxNTMyMzQwOTc4LCJuYmYiOjE1MzExMzEzNzgsImp0aSI6IjRTVGJJcXROdndMWVJqSEsiLCJzdWIiOjQsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEifQ.tofS8pkgcIFWGeWDTWtBxDlv_s5fa1y-wx5HQYVBh8
        // all good so return the token
        return response()->json(compact('token'));
    }

    /****
     * 获取用户的信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function AuthenticatedUser()
    {
//        echo JWTAuth::getToken(); return;
        try {
            if (!$user = JWTAuth::parseToken()->authenticate()) {
                return response()->json(['user_not_found'], 404);
            }
        } catch (TokenExpiredException $e) {
            return response()->json(['token_expired']);
        } catch (TokenInvalidException $e) {
            return response()->json(['token_invalid']);
//            return response()->json(['token_invalid'], $e->getStatusCode());
        } catch (JWTException $e) {
            return response()->json(['token_absent']);
        }
        // the token is valid and we have found the user via the sub claim
        return response()->json(compact('user'));
    }
}